package com.kcwx.web.controller.system;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import com.kcwx.common.annotation.Log;
import com.kcwx.common.constant.UserConstants;
import com.kcwx.common.core.controller.BaseController;
import com.kcwx.common.core.domain.AjaxResult;
import com.kcwx.common.core.domain.entity.SysDept;
import com.kcwx.common.enums.BusinessType;
import com.kcwx.common.utils.StringUtils;
import com.kcwx.system.service.ISysDeptService;

import com.kcwx.shareddomain.common.dto.DeleteDto;
import com.kcwx.shareddomain.common.dto.DelParaValid;
import com.kcwx.shareddomain.system.query.SysDeptQuery;
import com.kcwx.shareddomain.system.dto.SysDeptEditDto;
import com.kcwx.system.dtomap.SysDeptMap;

/**
 * 部门信息
 * 
 */
@Api(tags = "系统管理-部门管理")
@RestController
@RequestMapping("/system/dept")
public class SysDeptController extends BaseController
{
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private SysDeptMap sysDeptMap;

    /**
     * 新增
     */
    @ApiOperation("新增")
    @PreAuthorize("@ss.hasPermi('system:dept:add')")
    @Log(title = "新增部门", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@Validated @RequestBody SysDeptEditDto dto)
    {
        SysDept dept=sysDeptMap.AddDtoToEntity(dto);
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
        {
            return error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(getUsername());
        int rowsAffect=deptService.insertDept(dept);
        return rowsAffect>0?success():error("新增失败");
    }

    /**
     * 修改
     */
    @ApiOperation("修改")
    @PreAuthorize("@ss.hasPermi('system:dept:edit')")
    @Log(title = "修改部门", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult edit(@Validated @RequestBody SysDeptEditDto dto)
    {
        SysDept dept=sysDeptMap.EditDtoToEntity(dto);
        Long deptId = dept.getId();
        deptService.checkDeptDataScope(deptId);
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
        {
            return error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        else if (dept.getParentId().equals(deptId))
        {
            return error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        }
        else if (dept.getStatus()==1&& deptService.selectNormalChildrenDeptById(deptId) > 0)
        {
            return error("该部门包含未停用的子部门！");
        }
        dept.setUpdateBy(getUsername());
        int rowsAffect=deptService.updateDept(dept);
        return rowsAffect>0?success():error("修改失败");
    }

    /**
     * 删除
     */
    @ApiOperation("删除")
    @PreAuthorize("@ss.hasPermi('system:dept:remove')")
    @Log(title = "删除部门", businessType = BusinessType.DELETE)
    @DeleteMapping("/remove")
    public AjaxResult remove(@RequestBody DeleteDto dto)
    {
        Long id=DelParaValid.validDel(dto);
        if (deptService.hasChildByDeptId(id))
        {
            return warn("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(id))
        {
            return warn("部门存在用户,不允许删除");
        }
        deptService.checkDeptDataScope(id);
        int rowsAffect=deptService.deleteDeptById(id,getUsername());
        return rowsAffect>0?success():error("删除失败");
    }
    /**
     * 获取部门列表
     */
    @ApiOperation("获取部门列表")
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @Log(title = "获取部门列表", businessType = BusinessType.OTHER)
    @PostMapping("/list")
    public AjaxResult list(@RequestBody SysDeptQuery dept)
    {
        List<SysDept> deptList = deptService.selectDeptList(dept);
        return success(deptList);
    }
    /**
     * 查询部门列表（排除节点）
     */
    @ApiOperation("查询部门列表（排除节点）")
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @Log(title = " 查询部门列表（排除节点）", businessType = BusinessType.OTHER)
    @GetMapping("/list/exclude/{deptId}")
    public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId)
    {
        List<SysDept> deptList = deptService.selectDeptList(new SysDeptQuery());
        deptList.removeIf(d -> d.getId().longValue() == deptId || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""));
        return success(deptList);
    }

    /**
     * 根据id获取详细信息
     */
    @ApiOperation("获取详细信息")
    @PreAuthorize("@ss.hasPermi('system:dept:query')")
    @Log(title = " 根据id获取部门", businessType = BusinessType.OTHER)
    @GetMapping("/getById")
    public AjaxResult getInfo(Long id)
    {
        deptService.checkDeptDataScope(id);
        return success(deptService.selectDeptById(id));
    }

}
